package org.jeecg.modules.demo.util;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生成订单流水号
 */
public class generateOddUtilXs {
    private static ReentrantLock lock = new ReentrantLock();

    /**
     * @param map  兑换申请表最大值
     * @param name 单号前缀
     * @return
     */
    public static String createCode(Map<String, String> map, String name) {
        String resultCode = "";
        //上锁
        lock.lock();
        try{
            String maxCode = "";
            String laterCode = "";
            String str = map.get("maxCode");
    //        if(str!=null){
    //            StringBuffer stringBuffer = new StringBuffer(str);
    //            maxCode = stringBuffer.substring(2,10);
    //            laterCode = stringBuffer.substring(10,stringBuffer.length());
    //        }
            if (str != null && str != "") {
                StringBuffer stringBuffer = new StringBuffer(str);

                maxCode = stringBuffer.substring(stringBuffer.lastIndexOf("_")+1,stringBuffer.length()-4);
                laterCode = stringBuffer.substring(stringBuffer.length()-4,stringBuffer.length());

    //            maxCode = stringBuffer.substring(name.length(), name.length() + 8);
    //            laterCode = stringBuffer.substring(name.length() + 8, stringBuffer.length());
            }
            //指定生成的时间格式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String preCode = simpleDateFormat.format(new Date());
            //如果如果当天有生成的编码，直接在尾号加1；如果没有直接生成新的编码
            if (maxCode != null && maxCode.contains(preCode)) {
                Integer endCode = Integer.parseInt(laterCode); // 截取字符串最后四位，结果:0001
                //计算结果
                endCode = endCode + 10000 + 1;  // 结果10002
                resultCode = name + preCode + endCode.toString().substring(1);// 把10002首位的1去掉，再拼成201911010002字符串
            } else {
                resultCode = name + preCode + "0001";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
        return resultCode;
    }

//    public static void main(String[] args) {
//        String laterCode = "";
//        String name = "TSsZJ";
//        String name1 = "ZZJ";
//        String maxCode = "TSsZJ202206280001";
//        StringBuffer stringBuffer = new StringBuffer(maxCode);
//        int i = name.length() - name1.length();
//        maxCode = stringBuffer.substring(name.length(), name.length() + 8);
//        laterCode = stringBuffer.substring(name.length() + 8, stringBuffer.length());
//        System.out.println(name + maxCode + laterCode);
//        System.out.println(maxCode);
//        System.out.println(laterCode);
//    }

}
